package cn.jorian.framework.service.impl;

import cn.jorian.framework.bean.LoginUser;
import cn.jorian.framework.bean.ResponseResult;
import cn.jorian.framework.entity.User;
import cn.jorian.framework.service.LoginService;
import cn.jorian.framework.util.JwtUtil;
import cn.jorian.framework.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult<HashMap<String, String>> login(User user) {
        ResponseResult<HashMap<String, String>> responseResult = new ResponseResult<>();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            responseResult.setCode("-1");
            responseResult.setMessage("用户名或密码错误!");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        responseResult.setCode("200");
        responseResult.setMessage("成功");
        responseResult.setData(map);
        return responseResult;
    }

    @Override
    public ResponseResult<HashMap<String, String>> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User loginUser = (User) authentication.getPrincipal();
        Integer userid = loginUser.getId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult<>("true", "200","退出成功");
    }
}
